<script lang="ts" setup>
import { computed, ref, onMounted } from 'vue';
import {
  Button,
  Card,
  Col,
  Row,
  Select,
  SelectOption,
  Space,
  Modal,
  Form,
  FormItem,
  Input,
  DatePicker,
  TimePicker,
  message,
  Tooltip,
  Tag,
  Badge,
} from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';
import dayjs from 'dayjs';

const viewMode = ref('month');
const currentDate = ref(dayjs());
const selectedResource = ref('all');
const showScheduleModal = ref(false);
const selectedDate = ref('');
const selectedTimeSlot = ref('');
const scheduleForm = ref({
  resourceName: '',
  customerName: '',
  startTime: '',
  endTime: '',
  remark: '',
});

// 资源选项
const resourceOptions = [
  { label: '全部资源', value: 'all' },
  { label: '豪华套房', value: 'suite' },
  { label: '标准客房', value: 'room' },
  { label: '温泉池', value: 'hotspring' },
  { label: 'VIP包间', value: 'vip' },
  { label: '会议室', value: 'meeting' },
];

// 模拟排期数据
const mockSchedules = [
  {
    id: '1',
    resourceId: 'suite',
    resourceName: '豪华套房',
    customerName: '张三',
    date: '2024-03-15',
    startTime: '14:00',
    endTime: '16:00',
    status: 'CONFIRMED',
    remark: 'VIP客户',
    businessType: 'HOTEL',
    color: '#1890ff',
  },
  {
    id: '2',
    resourceId: 'hotspring',
    resourceName: '温泉池',
    customerName: '李四',
    date: '2024-03-15',
    startTime: '15:00',
    endTime: '17:00',
    status: 'PENDING',
    remark: '',
    businessType: 'HOT_SPRING',
    color: '#52c41a',
  },
  {
    id: '3',
    resourceId: 'vip',
    resourceName: 'VIP包间',
    customerName: '王五',
    date: '2024-03-15',
    startTime: '18:00',
    endTime: '20:00',
    status: 'CONFIRMED',
    remark: '生日宴请',
    businessType: 'RESTAURANT',
    color: '#722ed1',
  },
  {
    id: '4',
    resourceId: 'meeting',
    resourceName: '会议室A',
    customerName: '培训部',
    date: '2024-03-16',
    startTime: '09:00',
    endTime: '17:00',
    status: 'CONFIRMED',
    remark: '员工培训',
    businessType: 'TRAINING',
    color: '#faad14',
  },
  {
    id: '5',
    resourceId: 'room',
    resourceName: '标准客房101',
    customerName: '赵六',
    date: '2024-03-17',
    startTime: '14:00',
    endTime: '12:00',
    status: 'CONFIRMED',
    remark: '商务出差',
    businessType: 'HOTEL',
    color: '#1890ff',
  },
];

// 计算属性
const currentMonthText = computed(() => {
  return currentDate.value.format('YYYY年MM月');
});

const filteredSchedules = computed(() => {
  if (selectedResource.value === 'all') {
    return mockSchedules;
  }
  return mockSchedules.filter(
    (schedule) => schedule.resourceId === selectedResource.value,
  );
});

const calendarWeeks = computed(() => {
  const startOfMonth = currentDate.value.startOf('month');
  const endOfMonth = currentDate.value.endOf('month');
  const startOfCalendar = startOfMonth.startOf('week');
  const endOfCalendar = endOfMonth.endOf('week');

  const weeks = [];
  let currentWeek = [];
  let currentDay = startOfCalendar;

  while (
    currentDay.isBefore(endOfCalendar) ||
    currentDay.isSame(endOfCalendar, 'day')
  ) {
    const dayData = {
      date: currentDay.format('YYYY-MM-DD'),
      dayNumber: currentDay.date(),
      isCurrentMonth: currentDay.month() === currentDate.value.month(),
      isToday: currentDay.isSame(dayjs(), 'day'),
      schedules: getSchedulesForDate(currentDay.format('YYYY-MM-DD')),
    };

    currentWeek.push(dayData);

    if (currentDay.day() === 6) {
      weeks.push(currentWeek);
      currentWeek = [];
    }

    currentDay = currentDay.add(1, 'day');
  }

  if (currentWeek.length > 0) {
    weeks.push(currentWeek);
  }

  return weeks;
});

// 时间轴视图数据
const timelineData = computed(() => {
  const hours = [];
  for (let i = 0; i < 24; i++) {
    const hour = i.toString().padStart(2, '0');
    const schedules = getSchedulesForTimeSlot(hour);
    hours.push({
      hour,
      time: `${hour}:00`,
      schedules,
    });
  }
  return hours;
});

// 方法
const previousMonth = () => {
  currentDate.value = currentDate.value.subtract(1, 'month');
};

const nextMonth = () => {
  currentDate.value = currentDate.value.add(1, 'month');
};

const today = () => {
  currentDate.value = dayjs();
};

const getSchedulesForDate = (date: string) => {
  return filteredSchedules.value.filter((schedule) => schedule.date === date);
};

const getSchedulesForTimeSlot = (hour: string) => {
  return filteredSchedules.value.filter((schedule) => {
    const startHour = schedule.startTime.split(':')[0];
    return startHour === hour;
  });
};

const handleDateClick = (date: string) => {
  selectedDate.value = date;
  showScheduleModal.value = true;
};

const handleScheduleClick = (schedule: any) => {
  Modal.info({
    title: '排期详情',
    width: 600,
    content: `
      <div style="padding: 16px;">
        <p><strong>资源名称：</strong>${schedule.resourceName}</p>
        <p><strong>客户名称：</strong>${schedule.customerName}</p>
        <p><strong>日期：</strong>${schedule.date}</p>
        <p><strong>时间：</strong>${schedule.startTime} - ${schedule.endTime}</p>
        <p><strong>状态：</strong>${getStatusLabel(schedule.status)}</p>
        <p><strong>备注：</strong>${schedule.remark || '无'}</p>
      </div>
    `,
  });
};

const createSchedule = async () => {
  try {
    // 模拟创建排期
    const newSchedule = {
      id: Date.now().toString(),
      resourceId: scheduleForm.value.resourceName,
      resourceName: scheduleForm.value.resourceName,
      customerName: scheduleForm.value.customerName,
      date: selectedDate.value,
      startTime: scheduleForm.value.startTime,
      endTime: scheduleForm.value.endTime,
      status: 'PENDING',
      remark: scheduleForm.value.remark,
      businessType: 'HOTEL',
      color: '#1890ff',
    };

    mockSchedules.push(newSchedule);
    message.success('排期创建成功');
    showScheduleModal.value = false;
    resetScheduleForm();
  } catch (error) {
    message.error('创建失败');
  }
};

const resetScheduleForm = () => {
  scheduleForm.value = {
    resourceName: '',
    customerName: '',
    startTime: '',
    endTime: '',
    remark: '',
  };
};

const getStatusColor = (status: string) => {
  const colors = {
    CONFIRMED: 'green',
    PENDING: 'orange',
    CANCELLED: 'red',
  };
  return colors[status as keyof typeof colors] || 'default';
};

const getStatusLabel = (status: string) => {
  const labels = {
    CONFIRMED: '已确认',
    PENDING: '待确认',
    CANCELLED: '已取消',
  };
  return labels[status as keyof typeof labels] || status;
};

const getBusinessTypeColor = (type: string) => {
  const colors = {
    HOTEL: 'blue',
    HOT_SPRING: 'green',
    RESTAURANT: 'purple',
    TRAINING: 'orange',
  };
  return colors[type as keyof typeof colors] || 'default';
};

onMounted(() => {
  // 初始化
});
</script>

<template>
  <Card title="排期日历" :bordered="false">
    <!-- 工具栏 -->
    <div class="calendar-toolbar">
      <Row :gutter="16" align="middle">
        <Col :span="8">
          <Space>
            <Button @click="previousMonth">
              <IconifyIcon icon="mdi:chevron-left" />
            </Button>
            <Button @click="today">今天</Button>
            <Button @click="nextMonth">
              <IconifyIcon icon="mdi:chevron-right" />
            </Button>
            <span class="current-month">{{ currentMonthText }}</span>
          </Space>
        </Col>
        <Col :span="8">
          <Select
            v-model:value="viewMode"
            style="width: 120px"
            :options="[
              { label: '月视图', value: 'month' },
              { label: '周视图', value: 'week' },
              { label: '日视图', value: 'day' },
            ]"
          />
        </Col>
        <Col :span="8" style="text-align: right">
          <Select
            v-model:value="selectedResource"
            style="width: 150px"
            placeholder="选择资源"
            :options="resourceOptions"
          />
        </Col>
      </Row>
    </div>

    <!-- 月视图 -->
    <div v-if="viewMode === 'month'" class="month-view">
      <!-- 星期标题 -->
      <div class="week-header">
        <div
          class="week-day"
          v-for="day in ['日', '一', '二', '三', '四', '五', '六']"
          :key="day"
        >
          {{ day }}
        </div>
      </div>

      <!-- 日历网格 -->
      <div class="calendar-grid">
        <div
          v-for="week in calendarWeeks"
          :key="week[0].date"
          class="calendar-week"
        >
          <div
            v-for="day in week"
            :key="day.date"
            class="calendar-day"
            :class="{
              'other-month': !day.isCurrentMonth,
              today: day.isToday,
            }"
            @click="handleDateClick(day.date)"
          >
            <div class="day-number">{{ day.dayNumber }}</div>
            <div class="day-schedules">
              <div
                v-for="schedule in day.schedules.slice(0, 3)"
                :key="schedule.id"
                class="schedule-item"
                :style="{ backgroundColor: schedule.color }"
                @click.stop="handleScheduleClick(schedule)"
              >
                <Tooltip
                  :title="`${schedule.customerName} - ${schedule.startTime}-${schedule.endTime}`"
                >
                  <div class="schedule-content">
                    <div class="schedule-time">{{ schedule.startTime }}</div>
                    <div class="schedule-customer">
                      {{ schedule.customerName }}
                    </div>
                  </div>
                </Tooltip>
              </div>
              <div v-if="day.schedules.length > 3" class="more-schedules">
                +{{ day.schedules.length - 3 }} 更多
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 时间轴视图 -->
    <div v-else-if="viewMode === 'day'" class="timeline-view">
      <div class="timeline-container">
        <div
          v-for="timeSlot in timelineData"
          :key="timeSlot.hour"
          class="timeline-slot"
        >
          <div class="time-label">{{ timeSlot.time }}</div>
          <div class="time-content">
            <div
              v-for="schedule in timeSlot.schedules"
              :key="schedule.id"
              class="timeline-schedule"
              :style="{ backgroundColor: schedule.color }"
              @click="handleScheduleClick(schedule)"
            >
              <Tooltip
                :title="`${schedule.resourceName} - ${schedule.customerName}`"
              >
                <div class="schedule-info">
                  <div class="schedule-resource">
                    {{ schedule.resourceName }}
                  </div>
                  <div class="schedule-customer">
                    {{ schedule.customerName }}
                  </div>
                </div>
              </Tooltip>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 图例 -->
    <div class="calendar-legend">
      <div class="legend-item">
        <div class="legend-color" style="background-color: #1890ff"></div>
        <span>酒店</span>
      </div>
      <div class="legend-item">
        <div class="legend-color" style="background-color: #52c41a"></div>
        <span>温泉</span>
      </div>
      <div class="legend-item">
        <div class="legend-color" style="background-color: #722ed1"></div>
        <span>餐饮</span>
      </div>
      <div class="legend-item">
        <div class="legend-color" style="background-color: #faad14"></div>
        <span>培训</span>
      </div>
    </div>

    <!-- 创建排期弹窗 -->
    <Modal
      v-model:open="showScheduleModal"
      title="创建排期"
      @ok="createSchedule"
      @cancel="resetScheduleForm"
    >
      <Form :model="scheduleForm" layout="vertical">
        <FormItem label="资源名称" required>
          <Select
            v-model:value="scheduleForm.resourceName"
            placeholder="请选择资源"
            :options="resourceOptions.filter((r) => r.value !== 'all')"
          />
        </FormItem>
        <FormItem label="客户名称" required>
          <Input
            v-model:value="scheduleForm.customerName"
            placeholder="请输入客户名称"
          />
        </FormItem>
        <FormItem label="时间" required>
          <Space>
            <TimePicker
              v-model:value="scheduleForm.startTime"
              placeholder="开始时间"
              format="HH:mm"
            />
            <span>-</span>
            <TimePicker
              v-model:value="scheduleForm.endTime"
              placeholder="结束时间"
              format="HH:mm"
            />
          </Space>
        </FormItem>
        <FormItem label="备注">
          <Input.TextArea
            v-model:value="scheduleForm.remark"
            placeholder="请输入备注信息"
            :rows="3"
          />
        </FormItem>
      </Form>
    </Modal>
  </Card>
</template>

<style scoped>
.calendar-toolbar {
  margin-bottom: 16px;
  padding: 16px;
  background: #fafafa;
  border-radius: 6px;
}

.current-month {
  font-size: 16px;
  font-weight: 500;
  color: #1890ff;
}

.month-view {
  border: 1px solid #f0f0f0;
  border-radius: 6px;
}

.week-header {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  background: #fafafa;
  border-bottom: 1px solid #f0f0f0;
}

.week-day {
  padding: 12px;
  text-align: center;
  font-weight: 500;
  color: #666;
}

.calendar-grid {
  display: flex;
  flex-direction: column;
}

.calendar-week {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  border-bottom: 1px solid #f0f0f0;
}

.calendar-week:last-child {
  border-bottom: none;
}

.calendar-day {
  min-height: 120px;
  padding: 8px;
  border-right: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.2s;
}

.calendar-day:hover {
  background-color: #f5f5f5;
}

.calendar-day:last-child {
  border-right: none;
}

.calendar-day.other-month {
  background-color: #fafafa;
  color: #ccc;
}

.calendar-day.today {
  background-color: #e6f7ff;
}

.day-number {
  font-weight: 500;
  margin-bottom: 8px;
}

.day-schedules {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.schedule-item {
  padding: 2px 4px;
  border-radius: 3px;
  color: white;
  font-size: 11px;
  cursor: pointer;
  overflow: hidden;
}

.schedule-item:hover {
  opacity: 0.8;
}

.schedule-content {
  display: flex;
  flex-direction: column;
}

.schedule-time {
  font-weight: 500;
}

.schedule-customer {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.more-schedules {
  font-size: 10px;
  color: #999;
  text-align: center;
  padding: 2px;
}

.timeline-view {
  border: 1px solid #f0f0f0;
  border-radius: 6px;
  max-height: 600px;
  overflow-y: auto;
}

.timeline-container {
  display: flex;
  flex-direction: column;
}

.timeline-slot {
  display: flex;
  border-bottom: 1px solid #f0f0f0;
  min-height: 60px;
}

.timeline-slot:last-child {
  border-bottom: none;
}

.time-label {
  width: 80px;
  padding: 8px;
  background: #fafafa;
  border-right: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 500;
  color: #666;
}

.time-content {
  flex: 1;
  padding: 8px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.timeline-schedule {
  padding: 8px 12px;
  border-radius: 4px;
  color: white;
  cursor: pointer;
  min-width: 120px;
}

.timeline-schedule:hover {
  opacity: 0.8;
}

.schedule-info {
  display: flex;
  flex-direction: column;
}

.schedule-resource {
  font-weight: 500;
  font-size: 12px;
}

.schedule-customer {
  font-size: 11px;
  opacity: 0.9;
}

.calendar-legend {
  margin-top: 16px;
  display: flex;
  gap: 16px;
  justify-content: center;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.legend-color {
  width: 16px;
  height: 16px;
  border-radius: 3px;
}
</style>
